{{define "content"}}
<!-- Toast 通知组件 -->
<div id="toast-container" class="fixed top-4 right-4 z-50 space-y-2"></div>

<script>
    // 全局 Toast 函数
    window.showToast = function(message, type = 'info', duration = 3000) {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        
        const typeClasses = {
            success: 'bg-green-50 border-green-200 text-green-800',
            error: 'bg-red-50 border-red-200 text-red-800',
            warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
            info: 'bg-blue-50 border-blue-200 text-blue-800'
        };
        
        const iconClasses = {
            success: 'fas fa-check-circle text-green-500',
            error: 'fas fa-times-circle text-red-500',
            warning: 'fas fa-exclamation-triangle text-yellow-500',
            info: 'fas fa-info-circle text-blue-500'
        };
        
        toast.className = `max-w-sm w-full ${typeClasses[type]} border rounded-lg shadow-lg p-4 transform transition-all duration-300 translate-x-full opacity-0`;
        toast.innerHTML = `
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <i class="${iconClasses[type]}"></i>
                </div>
                <div class="ml-3 flex-1">
                    <p class="text-sm font-medium">${message}</p>
                </div>
                <div class="ml-4 flex-shrink-0">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(toast);
        
        // 触发动画
        setTimeout(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        }, 10);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }, duration);
    };
</script>

<!-- 模态框组件 -->
<div x-data="{ showModal: false, modalTitle: '', modalContent: '', modalType: 'info' }" x-show="showModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto" @keydown.escape.window="showModal = false">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" @click="showModal = false"></div>
        
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full sm:mx-0 sm:h-10 sm:w-10" :class="{
                        'bg-red-100': modalType === 'danger',
                        'bg-yellow-100': modalType === 'warning',
                        'bg-blue-100': modalType === 'info'
                    }">
                        <i class="fas" :class="{
                            'fa-exclamation-triangle text-red-600': modalType === 'danger',
                            'fa-exclamation-triangle text-yellow-600': modalType === 'warning',
                            'fa-info-circle text-blue-600': modalType === 'info'
                        }"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" x-text="modalTitle"></h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500" x-html="modalContent"></p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 text-base font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 sm:ml-3 sm:w-auto sm:text-sm" :class="{
                    'bg-red-600 hover:bg-red-700 focus:ring-red-500': modalType === 'danger',
                    'bg-yellow-600 hover:bg-yellow-700 focus:ring-yellow-500': modalType === 'warning',
                    'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500': modalType === 'info'
                }" @click="showModal = false">
                    确定
                </button>
                <button type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" @click="showModal = false">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>

<div x-data="userDetail()" x-init="init()">
    <!-- 页面标题和面包屑 -->
    <div class="mb-6">
        <nav class="flex mb-4" aria-label="Breadcrumb">
            <ol class="inline-flex items-center space-x-1 md:space-x-3">
                <li class="inline-flex items-center">
                    <a href="/dashboard" class="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600">
                        <i class="fas fa-home mr-2"></i>
                        首页
                    </a>
                </li>
                <li>
                    <div class="flex items-center">
                        <i class="fas fa-chevron-right text-gray-400 mx-2"></i>
                        <a href="/system" class="text-sm font-medium text-gray-700 hover:text-blue-600">系统管理</a>
                    </div>
                </li>
                <li>
                    <div class="flex items-center">
                        <i class="fas fa-chevron-right text-gray-400 mx-2"></i>
                        <a href="/system/users" class="text-sm font-medium text-gray-700 hover:text-blue-600">用户管理</a>
                    </div>
                </li>
                <li aria-current="page">
                    <div class="flex items-center">
                        <i class="fas fa-chevron-right text-gray-400 mx-2"></i>
                        <span class="text-sm font-medium text-gray-500">用户详情</span>
                    </div>
                </li>
            </ol>
        </nav>
        
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900 flex items-center">
                    <i class="fas fa-user-circle mr-3 text-blue-600"></i>
                    用户详情
                </h1>
                <p class="text-gray-600 mt-1">查看用户详细信息、角色权限和操作记录</p>
            </div>
            <div class="flex space-x-3">
                <button @click="refreshAllData()" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 flex items-center transition-colors" :disabled="isRefreshing">
                    <i class="fas fa-sync-alt mr-2" :class="{ 'fa-spin': isRefreshing }"></i>
                    <span x-show="!isRefreshing">刷新数据</span>
                    <span x-show="isRefreshing">刷新中...</span>
                </button>
                <a href="/system/users" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center transition-colors">
                    <i class="fas fa-arrow-left mr-2"></i>
                    返回用户列表
                </a>
                {{if .HasPermission "system.user.edit"}}
                <a :href="`/system/users/edit/${userId}`" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center transition-colors">
                    <i class="fas fa-edit mr-2"></i>
                    编辑用户
                </a>
                {{end}}
                {{if .HasPermission "system.user.delete"}}
                <button @click="confirmDelete()" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 flex items-center transition-colors" :disabled="isDeleting">
                    <span x-show="isDeleting">
                        <i class="fas fa-spinner fa-spin mr-2"></i>删除中...
                    </span>
                    <span x-show="!isDeleting">
                        <i class="fas fa-trash mr-2"></i>删除用户
                    </span>
                </button>
                {{end}}
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div x-show="isLoading" class="text-center py-16">
        <div class="inline-flex items-center px-6 py-4 bg-white rounded-lg shadow-sm">
            <i class="fas fa-spinner fa-spin text-blue-500 text-2xl mr-4"></i>
            <div class="text-left">
                <p class="text-lg font-medium text-gray-900">加载用户信息</p>
                <p class="text-sm text-gray-600">正在获取用户详细数据...</p>
            </div>
        </div>
    </div>

    <!-- 用户详情内容 -->
    <div x-show="!isLoading" class="space-y-6">
        <!-- 用户概览卡片 -->
        <div class="bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg shadow-lg overflow-hidden">
            <div class="px-6 py-8 text-white">
                <div class="flex items-center">
                    <div class="w-20 h-20 rounded-full bg-white bg-opacity-20 flex items-center justify-center text-white text-2xl font-bold mr-6" x-text="getUserInitials()"></div>
                    <div class="flex-1">
                        <h2 class="text-2xl font-bold" x-text="user.real_name || user.username"></h2>
                        <p class="text-blue-100 text-lg" x-text="'@' + user.username"></p>
                        <div class="flex items-center mt-2">
                            <span x-show="user.status === 'active'" class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                                <span class="w-2 h-2 rounded-full bg-green-500 mr-2"></span>
                                活跃用户
                            </span>
                            <span x-show="user.status === 'inactive'" class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800">
                                <span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span>
                                已停用
                            </span>
                            <span class="ml-4 text-blue-100 text-sm">
                                <i class="fas fa-calendar-alt mr-1"></i>
                                加入于 <span x-text="formatDate(user.created_at)"></span>
                            </span>
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-3xl font-bold" x-text="'#' + userId"></div>
                        <div class="text-blue-100 text-sm">用户ID</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
            <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-blue-500">
                <div class="flex items-center">
                    <div class="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center">
                        <i class="fas fa-sign-in-alt text-blue-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-2xl font-bold text-gray-900" x-text="userStats.login_count || 0"></p>
                        <p class="text-sm text-gray-600">登录次数</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-green-500">
                <div class="flex items-center">
                    <div class="w-12 h-12 rounded-lg bg-green-100 flex items-center justify-center">
                        <i class="fas fa-user-shield text-green-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-2xl font-bold text-gray-900" x-text="userRoles.length"></p>
                        <p class="text-sm text-gray-600">分配角色</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-yellow-500">
                <div class="flex items-center">
                    <div class="w-12 h-12 rounded-lg bg-yellow-100 flex items-center justify-center">
                        <i class="fas fa-key text-yellow-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-2xl font-bold text-gray-900" x-text="userPermissions.length"></p>
                        <p class="text-sm text-gray-600">拥有权限</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-purple-500">
                <div class="flex items-center">
                    <div class="w-12 h-12 rounded-lg bg-purple-100 flex items-center justify-center">
                        <i class="fas fa-clock text-purple-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-lg font-bold text-gray-900" x-text="getLastLoginText()"></p>
                        <p class="text-sm text-gray-600">最后登录</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧：基本信息 -->
            <div class="lg:col-span-1 space-y-6">
                <!-- 基本信息卡片 -->
                <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                    <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                        <h3 class="text-lg font-medium text-gray-900 flex items-center">
                            <i class="fas fa-user mr-2 text-blue-600"></i>
                            基本信息
                        </h3>
                    </div>
                    <div class="p-6 space-y-4">
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">用户名</span>
                            <div class="flex items-center">
                                <span class="text-sm text-gray-900" x-text="user.username"></span>
                                <button @click="copyToClipboard(user.username)" class="ml-2 text-gray-400 hover:text-gray-600" title="复制用户名">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">真实姓名</span>
                            <span class="text-sm text-gray-900" x-text="user.real_name || '未设置'"></span>
                        </div>
                        
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">邮箱地址</span>
                            <div class="flex items-center">
                                <span class="text-sm text-gray-900" x-text="user.email || '未设置'"></span>
                                <button x-show="user.email" @click="copyToClipboard(user.email)" class="ml-2 text-gray-400 hover:text-gray-600" title="复制邮箱">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">手机号码</span>
                            <div class="flex items-center">
                                <span class="text-sm text-gray-900" x-text="user.phone || '未设置'"></span>
                                <button x-show="user.phone" @click="copyToClipboard(user.phone)" class="ml-2 text-gray-400 hover:text-gray-600" title="复制手机号">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">账户状态</span>
                            <span x-show="user.status === 'active'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <span class="w-2 h-2 rounded-full bg-green-500 mr-1"></span>
                                正常
                            </span>
                            <span x-show="user.status === 'inactive'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                <span class="w-2 h-2 rounded-full bg-red-500 mr-1"></span>
                                停用
                            </span>
                        </div>
                        
                        <div class="flex items-center justify-between py-2 border-b border-gray-100">
                            <span class="text-sm font-medium text-gray-500">创建时间</span>
                            <span class="text-sm text-gray-900" x-text="formatDateTime(user.created_at)"></span>
                        </div>
                        
                        <div class="flex items-center justify-between py-2">
                            <span class="text-sm font-medium text-gray-500">更新时间</span>
                            <span class="text-sm text-gray-900" x-text="formatDateTime(user.updated_at)"></span>
                        </div>
                    </div>
                </div>

                <!-- 账户安全 -->
                <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                    <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                        <h3 class="text-lg font-medium text-gray-900 flex items-center">
                            <i class="fas fa-shield-alt mr-2 text-green-600"></i>
                            账户安全
                        </h3>
                    </div>
                    <div class="p-6 space-y-4">
                        <div class="flex items-center justify-between py-2">
                            <div class="flex items-center">
                                <i class="fas fa-key text-gray-400 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">密码强度</span>
                            </div>
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                安全
                            </span>
                        </div>
                        
                        <div class="flex items-center justify-between py-2">
                            <div class="flex items-center">
                                <i class="fas fa-clock text-gray-400 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">最后登录</span>
                            </div>
                            <span class="text-sm text-gray-900" x-text="user.last_login_at ? formatDateTime(user.last_login_at) : '从未登录'"></span>
                        </div>
                        
                        <div class="flex items-center justify-between py-2">
                            <div class="flex items-center">
                                <i class="fas fa-globe text-gray-400 mr-2"></i>
                                <span class="text-sm font-medium text-gray-700">登录IP</span>
                            </div>
                            <span class="text-sm text-gray-900" x-text="user.last_login_ip || '未知'"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：角色权限和活动记录 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 选项卡导航 -->
                <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                    <div class="border-b border-gray-200">
                        <nav class="-mb-px flex space-x-8 px-6" aria-label="Tabs">
                            <button @click="activeTab = 'roles'" class="py-4 px-1 border-b-2 font-medium text-sm transition-colors" :class="{
                                'border-blue-500 text-blue-600': activeTab === 'roles',
                                'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'roles'
                            }">
                                <i class="fas fa-user-shield mr-2"></i>
                                角色权限
                            </button>
                            <button @click="activeTab = 'logs'" class="py-4 px-1 border-b-2 font-medium text-sm transition-colors" :class="{
                                'border-blue-500 text-blue-600': activeTab === 'logs',
                                'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'logs'
                            }">
                                <i class="fas fa-history mr-2"></i>
                                操作日志
                            </button>
                            <button @click="activeTab = 'login'" class="py-4 px-1 border-b-2 font-medium text-sm transition-colors" :class="{
                                'border-blue-500 text-blue-600': activeTab === 'login',
                                'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'login'
                            }">
                                <i class="fas fa-sign-in-alt mr-2"></i>
                                登录记录
                            </button>
                        </nav>
                    </div>

                    <!-- 角色权限选项卡 -->
                    <div x-show="activeTab === 'roles'" class="p-6">
                        <div x-show="userRoles.length === 0" class="text-center py-12">
                            <i class="fas fa-user-tag text-gray-300 text-4xl mb-4"></i>
                            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无角色分配</h3>
                            <p class="text-gray-500">该用户尚未分配任何角色</p>
                        </div>
                        
                        <div x-show="userRoles.length > 0" class="space-y-4">
                            <template x-for="role in userRoles" :key="role.id">
                                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                                    <div class="flex items-start justify-between">
                                        <div class="flex items-center">
                                            <div class="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center text-blue-600 mr-4">
                                                <i class="fas fa-user-shield text-lg"></i>
                                            </div>
                                            <div>
                                                <h4 class="text-lg font-medium text-gray-900" x-text="role.display_name"></h4>
                                                <p class="text-sm text-gray-500 mt-1" x-text="role.description || '无描述'"></p>
                                                <div class="flex items-center mt-2">
                                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="{
                                                        'bg-green-100 text-green-800': role.status === 'active',
                                                        'bg-red-100 text-red-800': role.status === 'inactive'
                                                    }">
                                                        <span class="w-2 h-2 rounded-full mr-1" :class="{
                                                            'bg-green-500': role.status === 'active',
                                                            'bg-red-500': role.status === 'inactive'
                                                        }"></span>
                                                        <span x-text="role.status === 'active' ? '启用' : '禁用'"></span>
                                                    </span>
                                                    <span class="ml-3 text-xs text-gray-500">
                                                        创建于 <span x-text="formatDate(role.created_at)"></span>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        <button @click="showRolePermissions(role)" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                            查看权限
                                        </button>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                    <!-- 操作日志选项卡 -->
                    <div x-show="activeTab === 'logs'" class="p-6">
                        <div x-show="operationLogs.length === 0" class="text-center py-12">
                            <i class="fas fa-clipboard-list text-gray-300 text-4xl mb-4"></i>
                            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无操作记录</h3>
                            <p class="text-gray-500">该用户尚无任何操作记录</p>
                        </div>
                        
                        <div x-show="operationLogs.length > 0" class="space-y-4">
                            <template x-for="(log, index) in operationLogs" :key="index">
                                <div class="border-l-4 border-blue-500 bg-blue-50 p-4 rounded-r-lg">
                                    <div class="flex items-start justify-between">
                                        <div class="flex items-start">
                                            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-3 mt-1">
                                                <i class="fas fa-cog text-sm"></i>
                                            </div>
                                            <div>
                                                <h4 class="text-sm font-medium text-gray-900" x-text="log.action"></h4>
                                                <p class="text-sm text-gray-600 mt-1" x-text="log.description"></p>
                                                <div class="flex items-center mt-2 text-xs text-gray-500">
                                                    <i class="fas fa-clock mr-1"></i>
                                                    <span x-text="formatDateTime(log.created_at)"></span>
                                                    <span class="mx-2">|</span>
                                                    <i class="fas fa-globe mr-1"></i>
                                                    <span x-text="log.ip_address || '未知IP'"></span>
                                                </div>
                                            </div>
                                        </div>
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="{
                                            'bg-green-100 text-green-800': log.status === 'success',
                                            'bg-red-100 text-red-800': log.status === 'failed',
                                            'bg-yellow-100 text-yellow-800': log.status === 'warning'
                                        }">
                                            <span x-text="log.status === 'success' ? '成功' : (log.status === 'failed' ? '失败' : '警告')"></span>
                                        </span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                    <!-- 登录记录选项卡 -->
                    <div x-show="activeTab === 'login'" class="p-6">
                        <div x-show="loginHistory.length === 0" class="text-center py-12">
                            <i class="fas fa-history text-gray-300 text-4xl mb-4"></i>
                            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无登录记录</h3>
                            <p class="text-gray-500">该用户尚无任何登录记录</p>
                        </div>
                        
                        <div x-show="loginHistory.length > 0" class="space-y-4">
                            <template x-for="(record, index) in loginHistory" :key="index">
                                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                                    <div class="flex items-center justify-between">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4">
                                                <i class="fas fa-sign-in-alt"></i>
                                            </div>
                                            <div>
                                                <p class="text-sm font-medium text-gray-900" x-text="formatDateTime(record.login_time)"></p>
                                                <div class="flex items-center text-xs text-gray-500 mt-1">
                                                    <i class="fas fa-globe mr-1"></i>
                                                    <span x-text="record.ip_address || '未知IP'"></span>
                                                    <span class="mx-2">|</span>
                                                    <i class="fas fa-map-marker-alt mr-1"></i>
                                                    <span x-text="record.location || '未知位置'"></span>
                                                </div>
                                                <div class="text-xs text-gray-500 mt-1">
                                                    <i class="fas fa-desktop mr-1"></i>
                                                    <span x-text="record.user_agent || '未知设备'"></span>
                                                </div>
                                            </div>
                                        </div>
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="{
                                            'bg-green-100 text-green-800': record.status === 'success',
                                            'bg-red-100 text-red-800': record.status === 'failed'
                                        }">
                                            <span x-text="record.status === 'success' ? '成功' : '失败'"></span>
                                        </span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function userDetail() {
    return {
        // 数据
        userId: null,
        user: {},
        userRoles: [],
        userPermissions: [],
        userStats: {},
        loginHistory: [],
        operationLogs: [],
        
        // 状态
        isLoading: true,
        isRefreshing: false,
        isDeleting: false,
        activeTab: 'roles',
        
        // 初始化
        async init() {
            // 从URL获取用户ID
            const urlParts = window.location.pathname.split('/');
            this.userId = urlParts[urlParts.length - 1];
            
            // 并行加载数据
            await this.loadAllData();
            
            this.isLoading = false;
        },
        
        // 加载所有数据
        async loadAllData() {
            await Promise.all([
                this.loadUserData(),
                this.loadUserRoles(),
                this.loadUserPermissions(),
                this.loadUserStats(),
                this.loadLoginHistory(),
                this.loadOperationLogs()
            ]);
        },
        
        // 刷新所有数据
        async refreshAllData() {
            this.isRefreshing = true;
            try {
                await this.loadAllData();
                this.showToast('数据刷新成功', 'success');
            } catch (error) {
                this.showToast('刷新数据失败', 'error');
            } finally {
                this.isRefreshing = false;
            }
        },
        
        // 加载用户数据
        async loadUserData() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    this.user = result.data;
                } else {
                    throw new Error(result.message || '获取用户数据失败');
                }
            } catch (error) {
                console.error('加载用户数据失败:', error);
                this.showToast('加载用户数据失败: ' + error.message, 'error');
                setTimeout(() => {
                    window.location.href = '/system/users';
                }, 1500);
            }
        },
        
        // 加载用户角色
        async loadUserRoles() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}/roles`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.userRoles = result.data || [];
                } else {
                    console.warn('加载用户角色失败:', result.message);
                    this.userRoles = [];
                }
            } catch (error) {
                console.error('加载用户角色失败:', error);
                this.userRoles = [];
            }
        },
        
        // 加载用户权限
        async loadUserPermissions() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}/permissions`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.userPermissions = result.data || [];
                } else {
                    console.warn('加载用户权限失败:', result.message);
                    this.userPermissions = [];
                }
            } catch (error) {
                console.error('加载用户权限失败:', error);
                this.userPermissions = [];
            }
        },
        
        // 加载用户统计
        async loadUserStats() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}/stats`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.userStats = result.data || {};
                } else {
                    console.warn('加载用户统计失败:', result.message);
                    this.userStats = {};
                }
            } catch (error) {
                console.error('加载用户统计失败:', error);
                this.userStats = {};
            }
        },
        
        // 加载登录历史
        async loadLoginHistory() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}/login-history?limit=10`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.loginHistory = result.data || [];
                } else {
                    console.warn('加载登录历史失败:', result.message);
                    this.loginHistory = [];
                }
            } catch (error) {
                console.error('加载登录历史失败:', error);
                this.loginHistory = [];
            }
        },
        
        // 加载操作日志
        async loadOperationLogs() {
            try {
                const response = await fetch(`/api/v1/users/${this.userId}/operation-logs?limit=10`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.operationLogs = result.data || [];
                } else {
                    console.warn('加载操作日志失败:', result.message);
                    this.operationLogs = [];
                }
            } catch (error) {
                console.error('加载操作日志失败:', error);
                this.operationLogs = [];
            }
        },
        
        // 获取用户名首字母
        getUserInitials() {
            if (!this.user.real_name) return this.user.username ? this.user.username.charAt(0).toUpperCase() : 'U';
            
            // 支持中文姓名
            const name = this.user.real_name.trim();
            if (name.length === 0) return 'U';
            
            // 如果是中文，取最后一个字符（通常是名）
            if (/[\u4e00-\u9fa5]/.test(name)) {
                return name.charAt(name.length - 1);
            }
            
            // 英文取第一个字符
            return name.charAt(0).toUpperCase();
        },
        
        // 获取最后登录文本
        getLastLoginText() {
            if (!this.user.last_login_at) return '从未';
            
            const lastLogin = new Date(this.user.last_login_at);
            const now = new Date();
            const diffMs = now - lastLogin;
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            
            if (diffDays > 0) {
                return `${diffDays}天前`;
            } else if (diffHours > 0) {
                return `${diffHours}小时前`;
            } else if (diffMinutes > 0) {
                return `${diffMinutes}分钟前`;
            } else {
                return '刚刚';
            }
        },
        
        // 显示角色权限
        showRolePermissions(role) {
            // 这里可以实现显示角色权限的模态框
            this.showToast(`查看角色 "${role.display_name}" 的权限`, 'info');
        },
        
        // 复制到剪贴板
        async copyToClipboard(text) {
            try {
                await navigator.clipboard.writeText(text);
                this.showToast('已复制到剪贴板', 'success');
            } catch (error) {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    this.showToast('已复制到剪贴板', 'success');
                } catch (err) {
                    this.showToast('复制失败', 'error');
                }
                document.body.removeChild(textArea);
            }
        },
        
        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });
        },
        
        // 格式化日期时间
        formatDateTime(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        },
        
        // 确认删除用户
        confirmDelete() {
            if (confirm(`确定要删除用户 "${this.user.real_name || this.user.username}" 吗？\n\n此操作不可撤销，请谨慎操作！`)) {
                this.deleteUser();
            }
        },
        
        // 删除用户
        async deleteUser() {
            this.isDeleting = true;
            try {
                const response = await fetch(`/api/v1/users/${this.userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('用户删除成功', 'success');
                    setTimeout(() => {
                        window.location.href = '/system/users';
                    }, 1500);
                } else {
                    throw new Error(result.message || '删除用户失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                this.showToast('删除用户失败: ' + error.message, 'error');
            } finally {
                this.isDeleting = false;
            }
        },
        
        // 显示提示消息
        showToast(message, type = 'info') {
            if (window.showToast) {
                window.showToast(message, type);
            } else {
                // 降级方案
                console.log(`${type}: ${message}`);
                alert(message);
            }
        }
    };
}
</script>
{{end}}